<?php
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Regex as RegexValidator;
use Phalcon\Validation\Validator\Between;
use Phalcon\Validation\Validator\StringLength;

class SettingController extends CloudControllerBase
{
    public function systemConfigAction()
    {

    }

    public function subSystemConfigAction()
    {

    }

    /******************************    基础配置   ***********************************************************/

    private function _operationDictItem($opt)
    {

        $table = $opt["table"];
        $id = $opt["id"];
        $name = $opt["name"];
        $column = $opt["column"];
        $action = $opt["action"];
        //检查是否存在
        $count = $this->fetchColumn("select count(*) total from $table where $column='$name'");
        if ($count > 0) {
            $this->returnError("已经存在相同名称的项");
        } else {
            //执行更新
            $action = $opt["action"];
            if ($action == "update") {
                $this->update($table, array(
                    $column => $name
                ), "id=$id");
            }
            if ($action == "add") {
                $this->insert($table, array(
                    $column => $name
                ));
            }
            $this->returnSuccess("更新成功");
        }
    }


    public function dictListAction()
    {

        if ($this->isMonitorAdminUser()) {
            $table = $this->getPost("table");
            switch ($this->getRequestAction()) {
                case  $this::REQUEST_ACTION_ADD: {
                    $this->checkRequestParams(array(
                        array(
                            "key" => "name",
                            "type" => "presence",
                            "max" => 128,
                            "min" => 1,
                            "message" => "name在1-128之间"),
                    ));
                    $name = $this->getPost("name");
                    switch ($table) {
                        case "plane_area": {
                            $this->_operationDictItem(array(
                                "table" => "plane_area",
                                "name" => $name,
                                "column" => "name",
                                "action" => "add"
                            ));
                        };
                            break;
                        case "plane_model": {
                            $this->_operationDictItem(array(
                                "table" => "plane_model",
                                "name" => $name,
                                "column" => "name",
                                "action" => "add"
                            ));
                        };
                            break;
                        case  "plane_type": {
                            $this->_operationDictItem(array(
                                "table" => "plane_type",
                                "name" => $name,
                                "column" => "name",
                                "action" => "add"
                            ));
                        };
                            break;
                        case  "camera_model": {
                            $this->_operationDictItem(array(
                                "table" => "camera_model",
                                "name" => $name,
                                "column" => "name",
                                "action" => "add"
                            ));
                        };
                            break;

                    }
                };
                    break;
                case  $this::REQUEST_ACTION_DELETE: {
                    $this->checkRequestParams(array(
                        array(
                            "key" => "id",
                            "type" => "presence&number",
                            "message" => "id为空"),
                    ));
                    $id = $this->getPost("id");

                    $result = $this->execute("delete from $table where id=$id");
                    $this->saveDeleteLog($table,"","id=$id");
                    if ($result > 0) {
                        $this->returnSuccess("删除成功");
                    } else {
                        $this->returnError("删除失败");
                    }

                };
                    break;
                case  $this::REQUEST_ACTION_UPDATE: {
                    $data = null;
                    $this->checkRequestParams(array(
                        array(
                            "key" => "id",
                            "type" => "presence&number",
                            "message" => "id为空"),
                        array(
                            "key" => "name",
                            "type" => "presence",
                            "max" => 128,
                            "min" => 1,
                            "message" => "name在1-128之间"),
                    ));
                    $id = $this->getPost("id");
                    $name = $this->getPost("name");
                    switch ($table) {
                        case "plane_area": {
                            $this->_operationDictItem(array(
                                "table" => "plane_area",
                                "id" => $id,
                                "name" => $name,
                                "column" => "name",
                                "action" => "update"
                            ));
                        };
                            break;
                        case "plane_model": {
                            $this->_operationDictItem(array(
                                "table" => "plane_model",
                                "id" => $id,
                                "name" => $name,
                                "column" => "name",
                                "action" => "update"
                            ));
                        };
                            break;
                        case  "plane_type": {
                            $this->_operationDictItem(array(
                                "table" => "plane_type",
                                "id" => $id,
                                "name" => $name,
                                "column" => "name",
                                "action" => "update"
                            ));
                        };
                            break;
                        case  "camera_model": {
                            $this->_operationDictItem(array(
                                "table" => "camera_model",
                                "id" => $id,
                                "name" => $name,
                                "column" => "name",
                                "action" => "update"
                            ));
                        };
                            break;

                    }
                };
                    break;
                case  $this::REQUEST_ACTION_LIST: {

                    $data = null;
                    switch ($table) {
                        case "plane_area": {
                            $data = $this->getPlaneAreaInfo();
                        };
                            break;
                        case "plane_model": {
                            $data = $this->getPlaneModelInfo();
                        };
                            break;
                        case  "plane_type": {
                            $data = $this->getPlaneTypeInfo();
                        };
                            break;
                        case  "camera_model": {
                            $data = $this->getCameraTypeInfo();
                        };
                            break;
                    }
                    return $this->returnJson($data);
                };
                    break;
                case  $this->REQUEST_ACTION_DETAIL: {


                };
                    break;
            }


        }
    }

    /******************************    操作日志    ***********************************************************/

    //操作日志列表
    public function listOperationLogAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $tableName = "system_operation_log";
                $this->postQueryByPage(array(
                    "operation_user_id" => "操作用户ID",
                    "operation_user_info" => "操作用户",
                    "operation_type" => "操作类型",
                    "operation_content" => "操作内容",
                    "created_at" => "操作时间"
                ), $tableName, array(
                    ["operation_user_info", "like", "%", "%"],
                    ["operation_type", "like", "%", "%"],
                    ["operation_content", "like", "%", "%"],
                    ["operation_user_id", "=", "", ""]
                ), "created_at desc", "id");
            };
                break;
        }
    }

    /******************************    问题反馈    ***********************************************************/

    //问题反馈
    public function listRequestQuestionAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {

                $tableName = "(select l.*,user.nickname from question_request_log as l left join user on user.id=l.request_user_id)";
                $this->postQueryByPage(array(
                    "id" => "问题ID",
                    "question_title" => "问题",
                    "state" => "状态",
                    "question_desc" => "说明",
                    "nickname" => "提交用户",
                    "request_user_info" => "提交用户手机号",
                    "created_at" => "提交时间",
                ), $tableName, array(
                    ["id", "like", "%"],
                    ["state", "=", "", ""],
                    ["nickname", "like", "%", "%"],
                    ["question_title", "like", "%", "%"],
                    ["question_desc", "like", "%", "%"],
                    ["user_phone", "like", "%", "%", "request_user_info"],
                    ["created_at_start", ">=", "", "", "created_at"],
                    ["created_at_end", "<=", "", "", "created_at"],
                ), "state asc", "id");

            };
                break;
        }
    }

    public function requestQuestionAction()
    {
        $user = $this->getMonitorLoginUser();
        if ($user) {
            $title = $this->getPost("title");
            $content = $this->getPost("content");
            $result = $this->insert("question_request_log", array("question_title" => $title,
                "question_desc" => $content,
                "request_user_id" => $user->userId,
                "request_user_info" => $user->phone
            ));
            if ($result > 0) {
                $this->returnSuccess("感谢问题反馈,您的问题将会被尽快处理");
            } else {
                $this->returnSuccess("反馈问题错误");
            }
        }
    }


    public function filedItemChanged($table, $name, $value)
    {

        switch ($name) {

            case "operation_user_info": {
                if ($value == null) {
                    return "";
                }
            };
                break;
            case "state": {
                if (empty($value)) {
                    $value = 0;
                }
                switch ($value) {
                    case 0: {
                        return "待处理";
                    };
                        break;
                    case 1: {
                        return "处理中";
                    };
                        break;
                    case 2: {
                        return "已解决";
                    };
                        break;
                    case 3: {
                        return "已回复";
                    };
                        break;
                }
            };
                break;

        }
        return $value;
    }

    public function editorAction()
    {

        $question_id = $this->request->get("id");
        $sql = "SELECT q.*,u.nickname FROM question_request_log q LEFT JOIN user u ON q.request_user_id=u.id WHERE q.id=$question_id";

        $data = $this->fetchOne($sql);
        if (empty($data["state"])) {
            $data["state"] = "0";
        }
        $this->view->setVars(array("data" => $data));
    }

    /**
     *
     */
    public function replyHistoryAction()
    {
        $this->checkRequestParams(array(

            array(
                "key" => "question_id",
                "type" => "presence&number",
                "message" => "state为空"),
        ));
        $question_id = $this->getPost("question_id");
        $sql = "SELECT question_reply.* , user.nickname, question_request_log.state
                FROM question_reply 
                LEFT JOIN user
                ON question_reply.reply_user_id=user.id
                LEFT JOIN question_request_log
                ON question_reply.question_id=question_request_log.id
                WHERE question_id=$question_id
                ORDER BY created_at asc";
        $replyData = $this->fetchAll($sql);
        //获取附件列表
        for ($i=0; $i<sizeof($replyData); $i++){
            $f_id = $replyData[$i]['id'];
            $f_sql = "SELECT Q.file_url, Q.file_name FROM question_file AS Q WHERE Q.question_reply_id=$f_id";
            $f_data= $this->fetchAll($f_sql);
            if ($f_data){
                $replyData[$i]['fileData'] = $f_data;
            }
        }
        $cosData = array(
            'appid' => $this->filesCos['appid'],
            'region' => $this->filesCos['region'],
            'bucket' => $this->filesCos['bucket'],
            'url' => $this->filesCos['url'],
            'path' => $this->filesCos['path']
        );
        $comData = array($cosData, $replyData);
        $this->returnJson($comData);
    }

    public function addReplyMessageAction()
    {
        $this->checkRequestParams(array(
            array(
                "key" => "question_id",
                "type" => "presence&number",
                "message" => "question id 为空"),
            array(
                "key" => "text",
                "type" => "presence",
                "message" => "text为空"),
            array(
                "key" => "state",
                "type" => "presence&number",
                "message" => "state为空"),
        ));
        $question_id = $this->getPost("question_id");
        $text = $this->getPost("text");
        $state = $this->getPost("state");
        $fileList = $this->getPost("fileList");//附件列表
        $data = $this->fetchColumn("select id from question_request_log where id=$question_id");
        if (empty($data)) {
            $this->returnError("不存在该问题ID ");
        } else {
            $user = $this->getMonitorLoginUser();

            $this->insert("question_reply", array(
                "question_id" => $question_id,
                "reply_user_id" => $user->userId,
                "reply_content" => $text,
                "reply_state" => $state
            ));
            $lastId = $this->lastInsertId();
            if ($fileList){
                foreach ($fileList as $item){
                    $this->insert("question_file", array(
                        "file_name" => $item['Name'],
                        "file_key" => $item['Key'],
                        "file_url" => $item['Url'],
                        "question_reply_id" => $lastId
                    ));
                }
            }
            //如果是管理员的话,则更新
            if ($this->isMonitorAdminUser() ||
                $this->isMonitorSubsystemAdminUser()
            ) {
                $this->update("question_request_log",
                    array("state" => $state),
                    "id=$question_id");
            }
            $data = $this->fetchOne("select q.*,u.nickname from question_reply q left join user u on u.id=q.reply_user_id where q.id=$lastId");
            $f_sql = "SELECT Q.file_url, Q.file_name FROM question_file AS Q WHERE Q.question_reply_id=$lastId";
            $f_data = $this->fetchAll($f_sql);
            if ($f_data){
                $data['fileData'] = $f_data;
            }
            $this->returnJson($data);
        }
    }

    //上传校验
    public function sendAuthorizationAction()
    {
        $method = $this->getPost('method');
        $pathname = $this->getPost(('pathname'));
        $method = isset($method) ? $method : 'POST';
        $pathname = isset($pathname) ? $pathname: '/';
        $auth = $this->getAuthorization($method, $pathname);
        $this->returnJson($auth);
    }

    public function systemStatAction()
    {

        if ($this->isMonitorAdminUser()) {

            $dbName=$this->database->dbname;
            $sql = "SELECT TABLE_NAME,TRUNCATE (DATA_LENGTH / 1024 / 1024, 2) DATA_SIZE
FROM
    INFORMATION_SCHEMA. TABLES
WHERE
    TABLE_SCHEMA = '$dbName'
GROUP BY
    TABLE_NAME
ORDER BY
    DATA_LENGTH DESC limit 0,10;";
            $data = $this->fetchAll($sql);
            $this->view->setVars(array(
                "dbTableData" => json_encode($data)
            ));
        }


    }

    public function systemTestingAction()
    {

        if(!$this->isMonitorAdminUser()){
            $this->returnError("您没有权限访问该页面");
        }

    }
    public function updateSystemAction(){
        if(!$this->isMonitorAdminUser()){
            $this->returnError("您没有权限访问该页面");
        }else{
            $result=$this->curlRequest("http://127.0.0.1:12580/monitor_auto_update","get");
            if($result){
                $this->returnSuccess($result);
            }else{
                $this->returnSuccess("执行数据更新失败，请检查数据更新服务是否开启");
            }

        }
    }

    public function doTestAction()
    {
        $action = $this->getPost("action");
        $user = $this->getMonitorLoginUser();
        $userId = $user->userId;
        if ($action == "post_pc_assign_accpet") {
            $this->pc_push(array(
                'action' => 'pc_assign_accpet',
                'status' => '2',
                'data' => '',
                'message' => $user->name . '已接受了您的任务:测试任务',
            ), $userId, $userId);
        }
        if ($action == "post_pc_assign_deny") {
            $this->pc_push(array(
                'action' => 'pc_assign_deny',
                'status' => '2',
                'data' => '',
                'message' => $user->name . '已拒绝您的任务。',
            ), $userId, $userId);
        }
        if ($action == "post_pc_assign") {
            $this->pc_push(array(
                'action' => 'pc_assign',
                'status' => '2',
                'data' => '',
                'message' => $user->name . '向您分派了任务:测试任务',
            ), $userId, $userId);
        }
        $this->returnSuccess("操作成功");

    }


}